#include "book.h"
#include "common.h"
#include <string.h>
#include <stdio.h>

Book * Init_Book(){
	Book * NewBook;
	NewBook=(Book *)calloc(1,sizeof(Book));
	if(NewBook == NULL)
		return NewBook;
	NewBook->Name=NULL;
	NewBook->Author=NULL;
	NewBook->Total=0;
	NewBook->Stock=0;
	NewBook->ReaderList=NULL;
	return NewBook;
}

void Destroy_Book(Book * B){
	free(B->Name);
	free(B->Author);
	Destroy_Reader(B->ReaderList);
}

void SetISBN(Book * B,char isbn[]){
	for(int i=0; i<ISBN_SIZE; ++i){
		B->ISBN[i]=isbn[i];
	}
	B->ISBN[ISBN_SIZE]='\0';
}

void SetName(Book * B,char name[]){
	int length=strlen(name);
	char * ch=(char *)malloc(sizeof(char)*(length+1));
	if(B->Name != NULL){
		free(B->Name);
		B->Name=NULL;
	}
	strcpy(ch,name);
	B->Name=ch;
}

void SetAuthor(Book * B,char author[]){
	int length=strlen(author);
	char * ch=(char *)malloc(sizeof(char)*(length+1));
	if(B->Author != NULL){
		free(B->Author);
		B->Author=NULL;
	}
	strcpy(ch,author);
	B->Author=ch;
}

void SetStock(Book * B,unsigned int stock){
	B->Stock=stock;
}

void SetTotal(Book * B,unsigned int total){
	B->Total=total;
}

void AddReader(Book * B,Reader * R){
	R->Next=B->ReaderList;
	B->ReaderList=R;
}

void Show_Book(Book * B){
	printf("ISBN: %s  ",B->ISBN);
	printf("书名: 《%s》\n",B->Name);
	printf("作者: %s\n",B->Author);
	printf("馆存: %d   ",B->Stock);
	printf("总数: %d\n",B->Total);
}


// 13位数字编码 不允许长度不满或超出
// 不允许出现除数字外的字符
bool GetISBN(char *isbn){
	int i=0;
	char ch;
	do{
		ch=getchar();
		if(i<ISBN_SIZE) {
			isbn[i]=ch;
			if(ch < '0' || ch > '9'){
				if(ch != '\n')
					clear_buffer();
				return false;
			}
		}
		++i;
	}while(ch != '\n');
	isbn[ISBN_SIZE]='\0';
	if(i == ISBN_SIZE+1)
		return true;
	else
		return false;
}
